package com.lemon.cloud.websocket;

import com.lemon.cloud.websocket.config.WebSocketHandlerConfig;
import com.lemon.cloud.websocket.config.WebSocketProperties;
import lombok.AllArgsConstructor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.config.annotation.EnableWebSocket;
import org.springframework.web.socket.config.annotation.WebSocketConfigurer;
import org.springframework.web.socket.server.HandshakeInterceptor;

import java.util.List;

/**
 * @author HuangDS
 */
@Import({WebSocketHandlerConfig.class})
@EnableWebSocket
@Configuration(
        proxyBeanMethods = false
)
@AllArgsConstructor
public class WebSocketAutoConfiguration {

    private final WebSocketProperties webSocketProperties;

    @Bean
    @ConditionalOnMissingBean
    public WebSocketConfigurer webSocketConfigurer(List<HandshakeInterceptor> handshakeInterceptor, WebSocketHandler webSocketHandler) {
        return (registry) -> registry.addHandler(webSocketHandler, this.webSocketProperties.getPath())
                .setAllowedOrigins(this.webSocketProperties.getAllowOrigins())
                .addInterceptors(handshakeInterceptor.toArray(new HandshakeInterceptor[0]));
    }
}
